//
//  TrainListCtrl.m
//  Traveling
//
//  Created by 尹桥印 on 15/7/2.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//

#import "TrainListCtrl.h"
#import "TrainItemCell.h"
#import "HomeDataTool.h"

@interface TrainListCtrl ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *lastDayBtn;
@property (weak, nonatomic) IBOutlet UIButton *NextDayBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeBtn;
@property (weak, nonatomic) IBOutlet UITableView *tabView;

@property (nonatomic, copy) NSString *startCity;
@property (nonatomic, copy) NSString *endCity;
@property (nonatomic, strong) NSDate *date;

@property (nonatomic, strong) NSArray *itemArray;

@end

@implementation TrainListCtrl

-(instancetype)initWithStartCity:(NSString *)startCity entCity:(NSString *)endCity date:(NSDate *)date{
    self = [super init];
    if (self) {
        self.startCity = startCity;
        self.endCity = endCity;
        self.date = date;
        self.title = [NSString stringWithFormat:@"%@--%@",startCity,endCity];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tabView registerNib:[UINib nibWithNibName:@"TrainItemCell" bundle:nil] forCellReuseIdentifier:@"TrainItemCell"];
    self.tabView.rowHeight = 64;
    self.tabView.tableFooterView = [UIView new];
    [self requestDataWithDate:self.date];
}

-(void)requestDataWithDate:(NSDate *)date{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"start"] = self.startCity;
    params[@"end"] = self.endCity;
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    params[@"date"] = [fmt stringFromDate:date];
    self.timeBtn.text = [fmt stringFromDate:date];
    
    [DialogUtils showLoding];
    [HomeDataTool getTrainListWithStartCity:self.startCity endCity:self.endCity targetTime:self.timeBtn.text success:^(TrainResponse *result) {
        [DialogUtils hideLoding];
        if (result.isSucc) {
            self.itemArray = result.datas;
            [self.tabView reloadData];
        }else{
            [DialogUtils showTips:result.msg];
        }
        
    } failure:^(NSError *error) {
        [DialogUtils hideLoding];
        [DialogUtils showTips:@"加载失败"];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TrainItemCell *cell = [TrainItemCell cellWithTabelView:tableView];
    [cell setResult:self.itemArray[indexPath.row]];
    return cell;
}

- (IBAction)leftRightBtnClick:(UIButton *)sender {
    NSTimeInterval interval = 60*60*24;
    if (sender.tag==0) {
        self.date = [self.date dateByAddingTimeInterval:-interval];
    }else{
        self.date = [self.date dateByAddingTimeInterval:interval];
    }
    [self requestDataWithDate:self.date];
}



@end
